package com.android.infantschool.model.qiniu;

import android.util.Log;

import com.qiniu.android.http.ResponseInfo;
import com.qiniu.android.storage.Configuration;
import com.qiniu.android.storage.UpCompletionHandler;
import com.qiniu.android.storage.UploadManager;

import org.json.JSONObject;

import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;

public class QnUploadHelper {

    private static final String TAG = QnUploadHelper.class.getSimpleName();

    private static final String MAC_NAME = "HmacSHA1";
    private static final String ENCODING = "UTF-8";

    private static Configuration configuration;

    /**
     * 上传到七牛图片
     *
     * @param path     上传的本地图片
     * @param keys     在七牛上生成的图片名
     * @param token    要上传的token
     * @param callBack 回调接口
     */
    public static void uploadPic(final String path, final String keys, final String token, final UploadCallBack callBack) {
        configuration = new Configuration.Builder().build();
        try {
            UploadManager uploadManager = new UploadManager(configuration);
            uploadManager.put(path, keys, token,
                    new UpCompletionHandler() {
                        @Override
                        public void complete(String key, ResponseInfo info,
                                             JSONObject response) {
                            Log.d(TAG, "response = " + response);
                            if (info.isOK()) {
                                callBack.success(key);
                            } else {
                                callBack.fail(key, info);
                            }
                        }
                    }, null);
        } catch (Exception e) {
            e.printStackTrace();
            Log.e(TAG, "e:" + e.toString());
        }
    }

    /**
     * 使用 HMAC-SHA1 签名方法对对encryptText进行签名
     *
     * @param encryptText 被签名的字符串
     * @param encryptKey  密钥
     * @return
     * @throws Exception
     */
    public static byte[] HmacSHA1Encrypt(String encryptText, String encryptKey)
            throws Exception {
        byte[] data = encryptKey.getBytes(ENCODING);
        // 根据给定的字节数组构造一个密钥,第二参数指定一个密钥算法的名称
        SecretKeySpec secretKey = new SecretKeySpec(data, MAC_NAME);
        // 生成一个指定 Mac 算法 的 Mac 对象
        Mac mac = Mac.getInstance(MAC_NAME);
        // 用给定密钥初始化 Mac 对象
        mac.init(secretKey);
        byte[] text = encryptText.getBytes(ENCODING);
        // 完成 Mac 操作
        return mac.doFinal(text);
    }

    /**
     * 上传回调接口
     */
    public interface UploadCallBack {
        void success(String url);

        void fail(String key, ResponseInfo info);
    }

}